const path = require('path')

function gulptasksSounds($, gulp, buildFolder){
  const soundsDir = path.join(__dirname, '..', 'res_raw', 'sounds')
  const builtSoundsDir = path.join(__dirname, '..', 'res', 'sounds')

  const filters = ['loudnorm', 'volume=0.2']

  // 缓存已经打包的音频
  const fileCache = new $.cache.Cache({
    cacheDirName: 'shapezio-precompiled-sounds'
  })

  // 打包背景音乐
  gulp.task('sounds.encodeMusic', () => {
    return gulp
      .src([path.join(soundsDir, 'music', '**', '*.wav'), path.join(soundsDir, 'music', '**', '*.mp3')])
      .pipe(
        $.cache(
          $.fluentFfmpeg('mp3', cmd => {
            return cmd
              .audioBitrate(48)
              .audioChannels(1)
              .audioFrequency(22050)
              .audioCodec("libmp3lame");
          }),
          {
            name: 'music',
            fileCache
          }
        )
      )
      .pipe(gulp.dest(path.join(builtSoundsDir, 'music')))
  })

  // 打包UI按钮等的音频
  gulp.task('sounds.encodeUi', () => {
    return gulp
      .src([path.join(soundsDir, 'ui', '**', '*.wav'), path.join(soundsDir, 'ui', '**', '*.mp3')])
      .pipe(
        $.cache(
          $.fluentFfmpeg('mp3', cmd => {
            return cmd
              .audioBitrate(128)
              .audioChannels(1)
              .audioFrequency(22050)
              .audioCodec('libmp3lame')
              .audioFilters(filters)
          }),
          {
            name: 'uisounds',
            fileCache
          }
        )
      )
      .pipe(gulp.dest(path.join(builtSoundsDir, 'ui')))
  })

  // 打包游戏内的音频
  gulp.task('sounds.encodeGame', () => {
    return gulp
      .src([path.join(soundsDir, 'game', '**', '*.wav'), path.join(soundsDir, 'game', '**', '*.mp3')])
      .pipe(
        $.cache(
          $.fluentFfmpeg('mp3', cmd => {
            return cmd
              .audioBitrate(128)
              .audioChannels(1)
              .audioFrequency(22050)
              .audioCodec('libmp3lame')
              .audioFilters(filters)
          }),
          {
            name: 'gamesounds',
            fileCache
          }
        )
      )
      .pipe(gulp.dest(path.join(builtSoundsDir, 'game')))
  })

  // 将打包后的音频导入
  gulp.task('sounds.copy', () => {
    return gulp
      .src(path.join(builtSoundsDir, '**', '*.mp3'))
      .pipe($.cached('sounds.copy'))
      .pipe(gulp.dest(path.join(buildFolder, 'res', 'sounds')))
  })

  // 打包音频文件
  gulp.task('sounds.buildall', cb => {
    $.multiProcess(['sounds.encodeMusic', 'sounds.encodeUi', 'sounds.encodeGame'], cb, true);
  })

  gulp.task('sounds.dev', gulp.series('sounds.copy'))
}

module.exports = {
  gulptasksSounds
}